package database;

import java.util.Enumeration;
import java.util.Hashtable;



import dbmanager.DBManager;

public class RecordInsert
{
	private String table = "property_details";
	private Hashtable<Object, Object> newHash;
	private String query = null;
	private String insertFields = "";
	private String insertValues = "";

	DBManager database;
	
	public void setDatabase(DBManager database)
    {	
    	this.database = database;
    }
    
	
	public void setTableName(String tableName) 
    {
		this.table = tableName;	
    }
    

    /**
     * setInsertHash() method will sets the condition for the table query part.
     * */
    public void setHash(Hashtable<Object, Object> condition)
	{
    	this.newHash = new Hashtable<Object, Object>();
		this.newHash.putAll(condition);
		insertHashQuery(); // Calls the method for converting into the String.
	}

    /**
     * insertHashQuery() - It will creats the string from the Hash Table. Which get stores into the respected string variable.  
     * */    
    private void insertHashQuery() 
    {
    	try 
		{
			if(newHash.isEmpty())
			{
				System.out.println(" Field(s) or Value(s) doesn't exists into the supplied query ");
			}
			else
			{
				Enumeration keys = newHash.keys();
				while(keys.hasMoreElements())
				{
					String key = keys.nextElement().toString();
					String value = newHash.get(key).toString();
					insertFields = insertFields + key + ", ";
					insertValues = insertValues + " '"+ value + "', ";
				}
				insertFields = insertFields.substring(0, insertFields .length() - 2);
				insertValues = insertValues.substring(0, insertValues .length() - 2);
			}
		} 
		
		catch (Exception e) { }
	}
    
    public synchronized int getInsert()
    {
      try
  	  { 		  
  		  query = "INSERT INTO " + table;
  		  
  		  try 
  		  {
			if(insertFields.length() != 0)
				  query = query + "(" + insertFields + ")";
		  } 
  		  catch (Exception e)  { }
  		  
  		  try 
  		  {
			if(insertValues.length() != 0)
				  query = query + " VALUES (" + insertValues + ")";
		  } 
  		  catch (Exception e) { }
  		  
  		  System.out.println("The query is : " + query);
  		  int j = database.getInsert(query.toString());
  		  //System.out.println(j);
  		  if(j>0)
  		  {
  			 System.out.println("Data inserted successfully");
  		  }
  		  return j;
  	  }
  	  catch(Exception e)
  	  {
  		  e.printStackTrace();
  	  }
  	  return 0;
    }
    
    public static void main(String[] args) {
    	Hashtable<Object, Object> old = new Hashtable<Object, Object>();
    	old.put("mid", "9377");
		old.put("pid", "9");
		//newHash.put("vt", "knowledge");
		old.put("pv", "9322");
		
		DBManager database = new DBManager();
		database.getConnect();
		RecordInsert ri = new RecordInsert();
		ri.setDatabase(database);
		ri.setHash(old);
		ri.getInsert();
	}
}
